package com.ruoyi.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.constant.AsyncService;
import com.ruoyi.system.domain.TbListExpass;
import com.ruoyi.system.service.ITbListExpassService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Basetrans;
import com.ruoyi.system.service.IBasetransService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * Controller
 * 
 * @author ruoyi
 * @date 2025-01-18
 */
@RestController
@RequestMapping("/system/basetrans")
@Slf4j
public class BasetransController extends BaseController
{
    @Autowired
    private IBasetransService basetransService;

    @Autowired
    private ITbListExpassService expassService;

    @Autowired
    private AsyncService asyncService;

    /**
     * 查询列表
     */
    @PreAuthorize("@ss.hasPermi('system:basetrans:list')")
    @GetMapping("/list")
    public TableDataInfo list(Basetrans basetrans)
    {
        startPage();
        List<Basetrans> list = basetransService.selectBasetransList(basetrans);
        return getDataTable(list);
    }

    @PostMapping("/compare")
    public AjaxResult comparison(@RequestBody JSONObject json) {
        String exStartTime = json.getString("ex_start_time");
        String exEndTime = json.getString("ex_end_time");
        Basetrans basetrans = new Basetrans();
        Map<String, Object> params = new HashMap<>();
        params.put("beginTime", exStartTime);
        params.put("endTime", exEndTime);
//        params.put("spare3", 99);
        basetrans.setParams(params);

        List<Basetrans> list = basetransService.selectBasetransInfo(basetrans);
        if (list != null && !list.isEmpty()) {
            List<CompletableFuture<Void>> futures = list.stream()
                    .map(item -> asyncService.processBasetrans(item, exStartTime, exEndTime))
                    .collect(Collectors.toList());

            // 等待所有异步任务完成（可选）
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        } else {
            return success("没有需要更新的");
        }
//        if (list != null && !list.isEmpty()) {
//            for (Basetrans basetrans : list) {
//                QueryWrapper<ExPass> queryWrapper = Wrappers.query();
//                queryWrapper.eq("ex_vehicle_id", basetrans.getObuVehiclePlate());
//                queryWrapper.eq("card_id", basetrans.getEtcCardId());
//                System.out.println(basetrans.getEtcCardId());
//                List<ExPass> exPassList = exPassService.list(queryWrapper);
//                if (exPassList.size() > 1) {
//                    for (ExPass exPass : exPassList) {
//                        if (Objects.equals(exPass.getFee(), basetrans.getTotalToll())) {
//                            QueryWrapper<Basetrans> ro = new QueryWrapper<>();
//                            ro.eq("trade_id", basetrans.getTradeId());
//                            ro.eq("etc_card_id", basetrans.getEtcCardId());
//                            Basetrans ent = new Basetrans();
//                            ent.setSpare3(1L);
//                            basetransService.update(ent, ro);
//                        } else {
//                            QueryWrapper<Basetrans> ro = new QueryWrapper<>();
//                            ro.eq("trade_id", basetrans.getTradeId());
//                            ro.eq("etc_card_id", basetrans.getEtcCardId());
//                            Basetrans ent = new Basetrans();
//                            ent.setSpare3(2L);
//                            basetransService.update(ent, ro);
//                        }
//                    }
//                } else {
//                    if (!exPassList.isEmpty()) {
//                        if (Objects.equals(exPassList.get(0).getFee(), basetrans.getTotalToll())) {
//                            QueryWrapper<Basetrans> ro = new QueryWrapper<>();
//                            ro.eq("trade_id", basetrans.getTradeId());
//                            ro.eq("etc_card_id", basetrans.getEtcCardId());
//                            Basetrans ent = new Basetrans();
//                            ent.setSpare3(1L);
//                            basetransService.update(ent, ro);
//                        } else {
//                            QueryWrapper<Basetrans> ro = new QueryWrapper<>();
//                            ro.eq("trade_id", basetrans.getTradeId());
//                            ro.eq("etc_card_id", basetrans.getEtcCardId());
//                            Basetrans ent = new Basetrans();
//                            ent.setSpare3(2L);
//                            basetransService.update(ent, ro);
//                        }
//                    }
//                }
//            }
//        }
        // 统计


        //总数
        TbListExpass expass = new TbListExpass();
        expass.setParams(params);
        List<TbListExpass> allCount = expassService.selectTbListExpassCount(expass);

        List<Basetrans> yuCount = basetransService.selectBasetransCount(basetrans);
        //成功数
        params.put("spare3", 11);
        List<Basetrans> successCount = basetransService.selectBasetransCount(basetrans);
        //失败数
        params.put("spare3", 22);
        List<Basetrans> errorCount = basetransService.selectBasetransCount(basetrans);
        //未找到数
        params.put("spare3", 99);
        List<Basetrans> noneCount = basetransService.selectBasetransCount(basetrans);
        log.info("预交易数据 [{}] 比对情况：" +
                "总数 [{}] 条, 预交易数 [{}] 条, 比对成功数 [{}] 条, 比对失败数 [{}] 条, 未匹配数 [{}] 条, 转化率 {}, 金额校对成功转换率 {}。" +
                "未匹配数据如下：", DateUtils.dateTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD, exStartTime)), allCount.size(),
                yuCount.size(), successCount.size(), errorCount.size(), noneCount.size(), String.format("%.2f%%",
                        ((float)yuCount.size() / allCount.size()) * 100), String.format("%.2f%%",((float)successCount.size() / yuCount.size()) * 100)
                );

        return success();
    }

    /**
     * 导出列表
     */
    @PreAuthorize("@ss.hasPermi('system:basetrans:export')")
    @Log(title = "", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Basetrans basetrans)
    {
        List<Basetrans> list = basetransService.selectBasetransList(basetrans);
        ExcelUtil<Basetrans> util = new ExcelUtil<Basetrans>(Basetrans.class);
        util.exportExcel(response, list, "数据");
    }

    /**
     * 获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:basetrans:query')")
    @GetMapping(value = "/{tradeId}")
    public AjaxResult getInfo(@PathVariable("tradeId") String tradeId)
    {
        return success(basetransService.selectBasetransByTradeId(tradeId));
    }

    /**
     * 新增
     */
    @PreAuthorize("@ss.hasPermi('system:basetrans:add')")
    @Log(title = "", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Basetrans basetrans)
    {
        return toAjax(basetransService.insertBasetrans(basetrans));
    }

    /**
     * 修改
     */
    @PreAuthorize("@ss.hasPermi('system:basetrans:edit')")
    @Log(title = "", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Basetrans basetrans)
    {
        return toAjax(basetransService.updateBasetrans(basetrans));
    }

    /**
     * 删除
     */
    @PreAuthorize("@ss.hasPermi('system:basetrans:remove')")
    @Log(title = "", businessType = BusinessType.DELETE)
	@DeleteMapping("/{tradeIds}")
    public AjaxResult remove(@PathVariable String[] tradeIds)
    {
        return toAjax(basetransService.deleteBasetransByTradeIds(tradeIds));
    }
}
